#include "files/file.h"

#include <cstdio>
#include <sys/stat.h>

namespace Tvimeg
{
	File::File(void)
		:	file(NULL)
	{
	}

	File::File(const FilePath& pathIn)
		:	FileItem(pathIn), file(NULL)
	{
	}

	File::File(const File& other)
		: FileItem(other), file(NULL)
	{
	}

	File::~File(void)
	{
		Close();
	}

	File& File::operator=(const File& other)
	{
		Close();

		FileItem::operator=(other);
		return *this;
	}

	bool File::Exists(void) const
	{
		return FileItem::Exists(false);
	}

	size_t File::GetSize(void) const
	{
		struct stat data;
		if (stat(GetPath().c_str(), &data) == 0)
		{
			return data.st_size;;
		}
		else
		{
			return 0;
		}
	}

	bool File::Open(const Mode mode)
	{
		switch (mode)
		{
		case MODE_READ:
			return OpenRead();

		case MODE_WRITE:
			return OpenWrite();

		default:
			return false;
		}
	}

	bool File::OpenRead(void)
	{
		return OpenInternal("rb");
	}

	bool File::OpenWrite(void)
	{
		return OpenInternal("wb");
	}

	bool File::OpenInternal(const char* mode)
	{
		Close();

		file = std::fopen(GetPath().c_str(), mode);
		return IsOpen();
	}

	bool File::IsOpen(void) const
	{
		return file != NULL;
	}

	void File::Close(void)
	{
		if (IsOpen())
		{
			std::fclose(file);
			file = NULL;
		}
	}

	bool File::Read(void* data, const size_t sizeIn, size_t& sizeOut)
	{
		if (!IsOpen())
		{
			sizeOut = 0;
			return false;
		}

		sizeOut = std::fread(data, 1, sizeIn, file);
		return sizeOut > 0;
	}
}
